package com.bsh.utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * 生成流水号
 * @author gsh
 *
 */
public class PrimaryGenerater {
	private static PrimaryGenerater primaryGenerater = null;
    static int  serial=111111;
    static Random random = new Random();
    
	public static PrimaryGenerater getInstance() {
		if (primaryGenerater == null) {
			synchronized (PrimaryGenerater.class) {
				if (primaryGenerater == null) {
					primaryGenerater = new PrimaryGenerater();
				}
			}
		}
		return primaryGenerater;
	}

	/**
	 * 生成下一个编号
	 */
	public synchronized String next() {
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
        StringBuilder sb=new StringBuilder();
        sb.append("sn");
        sb.append(sf.format(date));		  
		if(serial>999999)serial=111111;
        String str = StringUtil.fitString(Integer.toString(serial++), 6,StringUtil.RIGHT);
        str = str.replace(" ", "0");
        sb.append(str);
        sf = new SimpleDateFormat("HHmmssSSS");
        sb.append(sf.format(date));		
        sb.append(random.nextInt(10));
        sb.append(random.nextInt(10));
        sb.append(random.nextInt(10));
		return sb.toString();
	}
	
	public static void main(String[] args) {
		for(int i=0;i<1000000;i++){
		  String sn = PrimaryGenerater.getInstance().next();
		  System.out.println(String.format("%s--%s", i,sn));
//			Random random = new Random();
//			int r1 = random.nextInt(10);
//			int r2 = random.nextInt(10);
//			int r3 = random.nextInt(10);
//			System.out.println(String.format("%s,%s,%s", r1,r2,r3));
		}
	}
}